import axios from 'axios'
import {
  TODO_ADD,
  TODO_CHANGE_DONE,
  TODO_CHANGE_TYPE,
  TODO_DEL,
  TODO_DEL_DONE,
} from './actionTypes'

// Action Creator(Action创建函数)
export const delById = (id) => {
  return { type: TODO_DEL, payload: id }
}

export const changeDoneById = (id) => {
  return { type: TODO_CHANGE_DONE, payload: id }
}

export const clearDone = () => {
  return { type: TODO_DEL_DONE }
}

export const changeType = (newType) => {
  return { type: TODO_CHANGE_TYPE, payload: newType }
}

export const addTodo = (todo) => {
  return { type: TODO_ADD, payload: todo }
}

// 模拟一个异步的 action
export const syncTodo = () => {
  // thunk 中间件要求，返回一个函数
  return async (dispatch) => {
    // 模拟一个异步请求
    await new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('成功')
      }, 5000)
    })
    // 模拟获取到请求结果后，再执行中间件内部的 dispatch 实现更新
    dispatch({ type: 'syncTodo', payload: '这是来自异步的action' })
  }
}

// 获取频道的异步 action
export const getChannels = () => {
  // thunk 中间件内部会调用下面这个函数
  return async (dispatch) => {
    // 发送请求业务代码
    const res = await axios.get(`http://geek.itheima.net/v1_0/channels`)
    console.log(`/v1_0/channels`, res)
    // 请求成功后，再调用 dispatch 更新 reducer 的状态
    dispatch({ type: 'saveChannel', payload: res.data.data.channels })
  }
}
